import {
  View,
  Image,
  StyleSheet,
  Dimensions,
  TouchableOpacity,
  Text,
} from 'react-native';
import React, { useEffect, useRef } from 'react';
import { useNavigation } from '@react-navigation/native';

const { width, height } = Dimensions.get('window');

const WelcomeSreen = () => {
  const navigation = useNavigation();

  const onPress = () => {
    console.log('跳过');
    // 清除定时器
    if (timerRef.current) {
      clearInterval(timerRef.current);
      timerRef.current = null;
    }
    navigation.navigate('Index');
  };
  const [currentIndex, setCurrentIndex] = React.useState(0);
  const timerRef = useRef<number | null>(null);

  const WELCOME_IMAGES = [
    'https://picsum.photos/seed/welcome1/800/1200',
    'https://picsum.photos/seed/welcome2/800/1200',
    'https://picsum.photos/seed/welcome3/800/1200',
    // 'https://picsum.photos/seed/welcome4/800/1200',
  ];

  useEffect(() => {
    if (currentIndex < WELCOME_IMAGES.length) {
      timerRef.current = setInterval(() => {
        setCurrentIndex(prevIndex => prevIndex + 1);
      }, 2000);
    }

    return () => {
      if (timerRef.current) {
        clearInterval(timerRef.current);
        timerRef.current = null;
      }
    };
  }, [currentIndex, WELCOME_IMAGES.length]);

  useEffect(() => {
    console.log(currentIndex);

    if (currentIndex === WELCOME_IMAGES.length) {
      // 清除定时器
      onPress();
    }
  }, [currentIndex, WELCOME_IMAGES.length]);

  return (
    <View>
      <Image
        style={styles.bgImage}
        source={{
          uri: WELCOME_IMAGES[currentIndex],
        }}
      />
      {/* 跳过按钮 */}
      <TouchableOpacity style={styles.button} onPress={onPress}>
        <Text>跳过</Text>
      </TouchableOpacity>
    </View>
  );
};

const styles = StyleSheet.create({
  bgImage: {
    width: width,
    height: height,
  },
  button: {
    position: 'absolute',
    top: 20,
    right: 20,
    backgroundColor: 'rgba(255,255,255,0.5)',
    padding: 10,
    borderRadius: 5,
  },
});

export default WelcomeSreen;
